package com.aegis.common.master.sr.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.aegis.common.master.redis.config.NodeConfig;
import com.aegis.common.master.redis.listener.MasterChangeListener;
import com.aegis.common.master.redis.main.NodeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @Author wx
 *
 * @Version 1.0
 */
@Configuration
@EnableConfigurationProperties(MasterRedisProperties.class)
public class MasterRedisConfig {

    @Autowired
    private Environment evironment;


    @Bean
    @ConditionalOnMissingBean(MasterChangeListener.class)
    public MasterChangeListener masterChangeListener() {
        return new DefaultMasterChangeListener();
    }

    @Bean
    @ConditionalOnBean(MasterChangeListener.class)
    public NodeManager nodeManager(MasterRedisProperties properties, MasterChangeListener masterChangeListener) {
        NodeConfig nodeConfig = new NodeConfig();
        BeanUtil.copyProperties(properties, nodeConfig);
        if (properties.getPort() == null) {
            String port = evironment.getProperty("server.port");
            if (StrUtil.isBlank(port)) {
                throw new RuntimeException("端口读取异常");
            }
            nodeConfig.setPort(Integer.parseInt(port));
        }
        return NodeManager.getInstance().init(nodeConfig, masterChangeListener);
    }

}
